package com.cari.oa.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.cari.oa.domain.NotificationEntity;
import com.cari.oa.util.StrUtils;

@Repository
public class NotificationDao  extends BaseDao<NotificationEntity>{
   
	/**
	 * 查询指定接收人的所有未读的信息
	*@param toUser
	*@return
	*@author hjx
	*@date 2013-5-8下午3:29:21
	 */
	public Long getListByToUser(String toUser)
	{
		Query query = getSession().createQuery("select count(*) from NotificationEntity where toUser = :toUser and isRead = :isRead");
        query.setString("toUser", toUser);
        query.setInteger("isRead", 1);
		return (Long)query.uniqueResult();
	}
	
	/**
	 * 分页查询信息
	*@param toUser
	*@param isRead
	*@param page
	*@param size
	*@return
	*@author hjx
	*@date 2013-5-8下午3:39:38
	 */
	public List<NotificationEntity> getPage(String toUser, int isRead, String title, int page, int size) {
    	
    	List<Object> params = new ArrayList<Object>();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("from NotificationEntity n where 1=1 ");

        if(StrUtils.isNotEmpty(toUser)) {
            stringBuilder.append("and n.toUser like ? ");
            params.add("%" + toUser + "%");
        }

        if(StrUtils.isNotEmpty(title)) {
            stringBuilder.append("and n.title like ? ");
            params.add("%" + title + "%");
        }    
    	stringBuilder.append("and n.isRead = ? ");
    	params.add(isRead);
        return getPage(stringBuilder.toString(), page, size, params.toArray());
    }
    
    /**
     * 获取满足条件的记录数
    *@param toUser
    *@param isRead
    *@return
    *@author hjx
    *@date 2013-5-8下午3:40:03
     */
    public long getCount(String toUser, int isRead, String title)
    {
    	
    	List<Object> params = new ArrayList<Object>();
        StringBuilder hql = new StringBuilder();
		hql.append("select count(*) from NotificationEntity n where 1=1 ");
	    if(StrUtils.isNotEmpty(toUser)) {
		     hql.append("and n.toUser like ? ");
             params.add("%" + toUser + "%");
        }
        if(StrUtils.isNotEmpty(title)) {
        	 hql.append("and n.title like ? ");
             params.add("%" + title + "%");
        }    
        hql.append("and n.isRead = ? ");
    	params.add(isRead);
        Query query = getSession().createQuery(hql.toString());
        for (int i = 0; i < params.size(); i++) {
            query.setParameter(i, params.get(i));
        }
        return (Long)query.uniqueResult();
    }
} 
